package de.ama.view;

import de.ama.crawler.Entry;
import de.ama.crawler.Store;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Dialog extends JDialog {

    private Entry entry;

    public Dialog() {
        super(AppWindow.get(), true);
        setBounds(1, 1, 1000, 810);
        initListener();
    }

    Component initComponent(Component c){
        c.setBackground(Color.DARK_GRAY);
        c.setForeground(Color.GRAY);
        c.setFont(new Font("Arial",Font.BOLD,14));
        if (c instanceof JTextField) {
            JTextField tf = (JTextField) c;
            tf.setCaretColor(Color.WHITE);
        }
        if (c instanceof JTextArea) {
            JTextArea area = (JTextArea) c;
            area.setLineWrap(true);
            area.setWrapStyleWord(true);
            area.setSize(new Dimension(450, 390));
        }
        return c;
    }

    public void setDataToGui(Entry aEntry) {
        entry = aEntry;
        if(entry.isAmbigous()){
            SelectPanel selectPanel = new SelectPanel(this);
            setContentPane(selectPanel);
            selectPanel.showData(entry);
        } else {
            DetailPanel detailPanel = new DetailPanel(this);
            JScrollPane scrollPane = new JScrollPane(detailPanel);
            scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
            setContentPane(scrollPane);
            detailPanel.showData(entry);
        }
        validate();
    }


    private void initListener() {
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });


    }

    void searchAgain(String txt) {
        CursorController.startWaitCursor((JComponent) getContentPane());
        try {
            entry.setSearchString(txt);
            Store.get().updateEntry(entry);
            setDataToGui(entry);
        } finally {
            CursorController.stopWaitCursor((JComponent) getContentPane());
        }
    }

    void onCancel() {
        dispose();
    }

    public Entry getEntry() {
        return entry;
    }
}
